/**
 *  EKology - An Ecosystem Simulation Framework
 *  Copyright (C) 2008  Aarón Tavío - aaron.tavio at gmail.com - ULPGC
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package net.ekology.core;

import net.ekology.ekosystem.*;
import net.ekology.ekosystem.datatypes.EKEvent;
import net.ekology.core.datatypes.AutomatonEvent;
import net.ekology.core.datatypes.Automaton;

import java.util.*;
import java.io.*;


/**
 * The <code>AgentAutomatonManager</code> is responsible of automaton's execution
 * <p>
 * Using an independent thread allows iterating over an automaton vector
 * generating automaton events processed by the agent.
 * 
 * @author Aarón Tavío - aaron.tavio at gmail.com
 * @version 1.0.0 - 20081019-1437
 */
public class AgentAutomatonManager implements Runnable, Serializable {
    private EKosystem oEKosystem;
    private Monitor oMonitor;
    private Hashtable<String,Automaton> htAgentAutomaton;
    transient private Thread oThread;
    private boolean bThreadSuspended;
    private boolean bStepMode;
    transient private Fecade oFecade;
    private int iLoopTime;
    private boolean bDrawing;
    
    
    public AgentAutomatonManager(EKosystem oEKosystem, Monitor oMonitor) {
        this.oEKosystem = oEKosystem;
        this.oMonitor = oMonitor;
        oThread = new Thread(this);
        bThreadSuspended = false;
        bStepMode = false;
        htAgentAutomaton = new Hashtable<String,Automaton>();
        oFecade = Fecade.getInstance();
        iLoopTime = 0;
        bDrawing = true;
    }
        
    
    /**
     * EKology's main loop
     */
    public void run() {
        long lTimestap;
        
        while (true) {
            try { // to avoid the deprecated methods Thread.suspend() & resume()
                if (bStepMode) {
                    bThreadSuspended = true;
                    bStepMode = false;
                }
                if (bThreadSuspended) {
                    synchronized(this) {
                        while (bThreadSuspended)
                            wait();
                    }
                }
            } catch (Exception ignore){}
            
            updateAutomatonTable();
            if (bDrawing) oFecade.repaintViewport();
            
            lTimestap = Calendar.getInstance().getTimeInMillis();
            
            oEKosystem.loopBegin();
            for(String sAgentID: htAgentAutomaton.keySet()) processAutomaton(sAgentID,iLoopTime);
            oEKosystem.loopEnd();
            
            iLoopTime = (int)(Calendar.getInstance().getTimeInMillis()-lTimestap);
            oEKosystem.addElapsedTime(iLoopTime);
            
            if (oMonitor.addElapsedTime(iLoopTime)) this.pause(); // if a breakpoint is triggered
        }
    }
    
    
    public void addAutomaton(String sAgentID, Automaton oAutomaton) {
        if (!htAgentAutomaton.containsKey(sAgentID)) htAgentAutomaton.put(sAgentID, oAutomaton);
    }
    
    
    public void removeAutomaton(String sAgentID) {
        htAgentAutomaton.remove(sAgentID);
    }
    
    
    /**
     * Passes control to the agent
     * <p>
     * First gets the ekosystem's events for the current agent, then <code>Automaton.step()</code>
     * obtaining the automaton events. These are passted to <code>EKosystem.attendAutomatonEvent()</code>
     * 
     * @param sAgentID the agent's identificator
     * @param iTimeSlice the time slice available to the agent. Measured in milliseconds
     * @see Automaton
     * @see EKosystem
     */
    private void processAutomaton(String sAgentID, int iTimeSlice) {
        Vector<EKEvent> vEKEvent;
        AutomatonEvent[] aAutomatonEvent;
        AutomatonEvent oAutomatonEvent;
        Automaton oAutomaton;
        int iTimeUsed;
        
        oAutomaton = htAgentAutomaton.get(sAgentID);
        iTimeUsed = 0;
        
        while (iTimeUsed < iTimeSlice) {
            vEKEvent = oEKosystem.getEvents(sAgentID,oAutomaton.getCurrentStateName());
            
            aAutomatonEvent = oAutomaton.step(vEKEvent);
            for(int i=0; i<aAutomatonEvent.length; i++) {
                oAutomatonEvent = aAutomatonEvent[i];
                iTimeUsed += oEKosystem.attendAutomatonEvent(sAgentID,oAutomatonEvent,iTimeSlice-iTimeUsed);
            }

        }
    }
    
    
    private void updateAutomatonTable() {
        Vector<String> vID;
        Agent[] aAgent;
        
        vID = new Vector<String>(htAgentAutomaton.keySet());
        // remove dead agents' automaton
        for(String sID: vID) {
            if (!oEKosystem.containsAgent(sID)) removeAutomaton(sID);
        }

        // add new agents' automaton
        aAgent = oEKosystem.getAgents();
        for(Agent oAgent: aAgent) {
            if (!htAgentAutomaton.containsKey(oAgent.getID()) && oAgent.getAutomaton() != null) addAutomaton(oAgent.getID(), oAgent.getAutomaton());
        }

    }
    
    public synchronized void setDrawing(boolean bValue) {
        bDrawing = bValue;
    }
    
    
    public synchronized void playResume() {
        if (oThread.isAlive()) {
            bThreadSuspended = false;
            notify();
        }
        else oThread.start();
    }
    
    public synchronized void step() {
        bThreadSuspended = false;
        bStepMode = true;
        if (oThread.isAlive()) notify();
        else oThread.start();
    }
    
    
    public synchronized void pause() {
        bThreadSuspended = true;
    }
    
    
    /**
     * Use to deserialize the object
     * 
     * @param in the input stream
     * @throws java.io.IOException
     * @throws java.lang.ClassNotFoundException
     */
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        
        oFecade = Fecade.getInstance();
        oThread = new Thread(this);
    }

}
